package com.ihrm.system.service;

import com.baidu.aip.util.Base64Util;
import com.ihrm.common.service.BaseService;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.QiniuUploadUtil;
import com.ihrm.domain.company.Department;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.User;
import com.ihrm.system.client.DepartmentFeignClient;
import com.ihrm.system.dao.RoleDao;
import com.ihrm.system.dao.UserDao;
import com.ihrm.system.utils.BaiduAiUtil;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.io.IOException;
import java.util.*;

@Service
public class UserService extends BaseService {
    @Autowired
    private UserDao userDao;
    
    @Autowired
    private RoleDao roleDao;
    
    @Autowired
    private IdWorker idWorker;
    
    @Autowired
    private DepartmentFeignClient departmentFeignClient;
    
    /**
     * 批量保存用户
     */
    @Transactional
    public void saveAll(List<User> list,String companyId,String companyName){
        for(User user:list){
            /**
             * 默认密码
             */
            user.setPassword(new Md5Hash("123456",user.getMobile(),3).toString());
            /**
             * id
             */
            user.setId(idWorker.nextId()+"");
            /**
             * 基本属性
             */
            user.setCompanyId(companyId);
            user.setCompanyName(companyName);
            user.setInServiceStatus(1);
            user.setEnableState(1);
            user.setLevel("user");
    
            /**
             * 填充部门的属性
             */
            Department department = departmentFeignClient.findByCode(user.getDepartmentId(), companyId);
            if(department!=null){
                user.setDepartmentId(department.getId());
                user.setDepartmentName(department.getName());
            }
            
            userDao.save(user);
        }
    }
    
    /**
     * 根据mobile查询用户
     */
    public User findByMobile(String mobile){
        return userDao.findByMobile(mobile);
    }
    
    /**
     * 保存用户
     */
    public void save(User user){
        String id=idWorker.nextId()+"";
        /**
         * 设置初始密码
         */
        user.setPassword("123456");
        String password=new Md5Hash("123456",user.getMobile(),3).toString();
        user.setLevel("user");
        user.setPassword(password);//设置初始密码
        user.setEnableState(1);
        user.setId(id);
        userDao.save(user);
    }
    
    /**
     * 更新用户
     */
    public void update(User user){
        User target=userDao.findById(user.getId()).get();
        target.setUsername(user.getUsername());
        target.setPassword(user.getPassword());
        target.setDepartmentId(user.getDepartmentId());
        target.setDepartmentName(user.getDepartmentName());
        userDao.save(target);
    }
    
    
    /**
     * 根据id查询用户
     */
    public User findById(String id){
        return userDao.findById(id).get();
    }
    
    /**
     * 根据企业id查询全部用户列表
     */
    public List<User> findAll(String companyId){
        return userDao.findAll(super.getSpec(companyId));
    }
    
    /**
     * 查询全部用户列表
     * 参数：map集合的形式
     *      hasDept
     *      departmentId
     *      companyId
     */
    public Page findAll(Map<String,Object> map,int page,int size){
        /**
         * 设置查询条件
         */
        Specification<User> spec = new Specification<User>(){
            /**
             * 动态拼接查询条件
             */
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> cq, CriteriaBuilder cb){
                List<Predicate> list=new ArrayList<>();
                /**
                 * 根据请求的companyId是否为空构造查询条件
                 */
                if(!StringUtils.isEmpty(map.get("companyId"))){
                    list.add((Predicate) cb.equal(root.get("companyId").as(String.class),(String)map.get("companyId")));
                }
                /**
                 * 根据请求的部门departmentId构造查询条件
                 */
                if(!StringUtils.isEmpty(map.get("departmentId"))){
                    list.add((Predicate) cb.equal(root.get("departmentId").as(String.class),(String)map.get("departmentId")));
                }
                if(!StringUtils.isEmpty(map.get("hasDept"))){
                    /**
                     * 根据请求的hasDept判断是否分配部门
                     *      0未分配(departmentId=null)
                     *      1已分配(departmentId!=null)
                     */
                    if("0".equals((String) map.get("hasDept"))){
                        list.add(cb.isNull(root.get("departmentId")));
                    }else {
                        list.add(cb.isNotNull(root.get("departmentId")));
                    }
                }
                return cb.and(list.toArray(new Predicate[list.size()]));
            }
        };
        /**
         * 分页
         */
        Page<User> pageUser=userDao.findAll(spec,new PageRequest(page-1,size));
        return pageUser;
    }
    
    /**
     * 根据id删除用户
     */
    public void deleteById(String id){
        userDao.deleteById(id);
    }
    
    /**
     * 分配角色
     */
    public void assignRoles(String userId,List<String> roleIds){
        /**
         * 根据id查询用户
         */
        User user = userDao.findById(userId).get();
        /**
         * 设置用户的角色集合
         */
        Set<Role> roles = new HashSet<>();
        for(String roleId:roleIds){
            Role role=roleDao.findById(roleId).get();
            roles.add(role);
        }
        /**
         * 设置用户和角色集合的关系
         */
        user.setRoles(roles);
        /**
         * 更新用户
         */
        userDao.save(user);
    }
    

    public String uploadImage(String id, MultipartFile file) throws IOException{
        /**
         * 根据id查询用户
         */
        User user = userDao.findById(id).get();
    
        /**
         * 将图片上传到七牛云存储，获取请求路径
         */
        String imgUrl = new QiniuUploadUtil().upload(user.getId(), file.getBytes());
    
        /**
         * 更新用户头像地址
         */
        user.setStaffPhoto(imgUrl);
        userDao.save(user);
        
        
        return imgUrl;
    }
    
}
